package com.online.taxi.order.implementation.zookeeperCurator;

import com.online.taxi.order.implementation.LockKey;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

/**
 * @Author:jiangqikun
 * @Date:2022/8/21 15:03
 **/

public class ZookeeperCuratorUse {

    @Autowired
    private CuratorFramework client;

    public void use(String orderId, String driverId) {
        // 生成 key
        LockKey key = LockKey.builder()
                .driverId(driverId)
                .orderId(orderId)
                .build();
        InterProcessMutex lock = new InterProcessMutex(client, orderId);

        try {
            if (lock.acquire(30, TimeUnit.SECONDS)) {
                // 执行业务代码

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                lock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


}
